# File: gameStateController
# By: Camiel Verschoor, Sander Nugteren & Erik van Egmond

from socket import *
import time
import gameController as gameC
import buttonController as buttonC
import threading

class stateController(threading.Thread):
    # VARIABLES
    f = open('/home/nao/naoinfo/NAOINFO.txt','r')
    robot = int(f.readline())-1
    team = int(f.readline())
    state = 0
    gcActive = True
    lastCheck = 0
    bc = buttonC.buttonController()
    gc = gameC.gameController(team)

    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
        self.on = True

    def __del__(self):
        self.run = False
        self.gc.close()

    def run(self):
        gcState = 0
        buttonState = 0
        while(self.on):
            # print 'gameStateController.py state: ' + str(self.state)
            self.gcActive = self.gc.controlledRefresh()
            self.lastCheck = time.time()
            
            if self.gcActive:
                gcState = self.gc.getGameState() #get phase from GameController
                buttonState = self.listenToButtons(buttonState) #moet die meegegeven worden?
                #zou misschien netter zijn als buttonState en gcState in dit object zitten?
                #zodat listenToButtons een soort setter voor buttonState zou zijn?
                if (buttonState == 10 or self.gc.getPenalty(self.robot, self.team)):
                    self.state = 10
                else:
                    self.state = gcState
            else:
                    
                while time.time() - self.lastCheck < 5:
                    buttonState = self.listenToButtons(buttonState) #moet die meegegeven worden?
                    self.state  = buttonState
        self.close()

    def getState(self):
        return self.state

    def listenToButtons(self, buttonState):
        if self.bc.getChestButton(): #change the phase if the ChestButton was pressed
            if(buttonState == 0):
                return 10
            elif(buttonState == 10):
                return 3
            elif(buttonState == 3):
                return 10
            else:
                return 3
        else:
            return buttonState

    def getSetup(self):
        return self.bc.getSetup()

    def setup(self, a = 0, b = 0):
        return self.bc.setup(a, b)

    # GET FUNCTIONS
    def getTeamNumber(self):
        return self.team

    def getRobotNumber(self):
        return self.robot

    # Closes thread
    def close(self):
        self.on = False
        self.gc.close()

# This code will only be executed if invoked directly. Not when imported from another file.
# It shows how to use this module
if __name__ == '__main__':
    sc = stateController("stateController")
    sc.start()
    now = time.time()
    while (sc.getState() != 4):
        pass
    sc.close()
